﻿'**************************
'Created By : Tran Nguyen Lam
'**************************
Imports System.Globalization
Imports hmweb.Services.cCommonFunction
Imports System.IO
Imports System.Math
Module GlobalFunction
    '-----Số Chuẩn Hệ Thống Là 123,456,789.123
    'Mỹ : 3.5 Việt Nam 3,5
    'Mỹ 124,456.78 Việt Nam 124.456,78
    Private CurrentCulture As String = "vi-vn"
    Public VietNam As CultureInfo = Globalization.CultureInfo.CreateSpecificCulture("vi-vn")
    Public US As CultureInfo = Globalization.CultureInfo.CreateSpecificCulture("en-us")
    Public ComputerName As String = Environment.MachineName.ToString
    Public LoginName As String = Environment.UserName.ToString
    Public Function ConvertDateToInt(ByVal Ngay As String) As Integer
        Dim aNgay As String() = Ngay.Split("/")
        Dim iThang As String
        Dim iNgay As String
        Dim Ngay_So As String
        If Integer.Parse(aNgay(1).Trim()) <= 9 Then
            iNgay = "0" & aNgay(1).Trim()
        Else
            iNgay = aNgay(1).Trim()
        End If
        If Integer.Parse(aNgay(0).Trim()) <= 9 Then
            iThang = "0" & aNgay(0).Trim()
        Else
            iThang = aNgay(0).Trim()
        End If
        Ngay_So = aNgay(2).Trim() & iThang & iNgay
        Try
            Return Integer.Parse(Ngay_So)
        Catch ex As Exception
            Return 0
        End Try
    End Function
    Function LamTron(ByVal n As Double, Optional ByVal dp As Integer = 0) As Double
        Return Floor(Abs(n * 10 ^ dp) + 0.5) * Sign(n) / 10 ^ dp
    End Function
    Public Function SDNMessageBox(ByVal text As String, ByVal caption As String, ByVal buttons As System.Windows.Forms.MessageBoxButtons, ByVal icon As System.Windows.Forms.MessageBoxIcon, ByVal defaultButton As System.Windows.Forms.MessageBoxDefaultButton) As DialogResult
        Try
            Dim result As DialogResult
            result = DevComponents.DotNetBar.MessageBoxEx.Show(text, caption, buttons, icon, defaultButton)
            Return result
        Catch ex As Exception

        End Try
    End Function
    Public Function Printer() As String
        Try
            Dim CurrentDir As String = Path.GetDirectoryName(Application.ExecutablePath)
            Dim PrinterName As String = ""
            Dim PrinterConfig As String = CurrentDir + "\PrinterDefault.txt"
            'check isExist PrinterConfig
            If File.Exists(PrinterConfig) Then
                PrinterName = System.IO.File.ReadAllText(PrinterConfig)
            Else
                PrinterName = ""
            End If
            Return PrinterName
        Catch ex As Exception
            Throw
        End Try
    End Function
    Public Function SaveNumber(ByVal Number As String, ByVal TypeNumber As String) As Single
        Try
            Select Case TypeNumber
                Case "N" Or "n"
                    'Luu Theo Kieu So Luong

                Case "P" Or "p"
                    'Luu Theo Kieu Gia Tien

            End Select
        Catch ex As Exception

        End Try
    End Function
    Public Function NgayTao() As String
        Try
            Return Format(Now, "dd/MM/yyy HH:mm:ss")
        Catch ex As Exception
            Throw
        End Try
    End Function
    Public Function NguoiTao() As String
        Try
            Return frmMain.UserName
        Catch ex As Exception
            Throw
        End Try
    End Function
    Public Function CurrentNumberFormat() As Boolean
        Try
            Dim culture As New CultureInfo(CultureInfo.CurrentCulture.Name)
            If culture.NumberFormat.NumberDecimalSeparator = "," And culture.NumberFormat.NumberGroupSeparator = "," Then
                Return True
            Else
                Return False
            End If
        Catch ex As Exception
            ShowError()
        End Try
    End Function
    'Số Lưu Xuống Database
    Public Function SaveNumber2Database(ByVal Number As String) As Single
        Try
            'Người ta nhập vào sẽ 124.456,78 ---> 124,456.78
            If Number.IndexOf(",") > 0 Then
                Dim MangSo() As String = Number.Split(",")
                Dim PhanChan As String = MangSo(0)
                Dim PhanLe As String = MangSo(1)
                Dim sRet As Single
                sRet = Single.Parse(PhanChan.Replace(".", "") & "." & PhanLe)
                Return sRet
            Else
                Return Single.Parse(Number.Replace(".", ""))
            End If
        Catch ex As Exception
            ShowError()
        End Try
    End Function
    'Số hiển thị lên Form
    Public Function DisplayNumberForm(ByVal Number As String, Optional ByVal ShowPercent As Boolean = False) As String
        Try
            If ShowPercent Then
                Return CDec(Number).ToString("N1", CultureInfo.CreateSpecificCulture("vi-vn"))
            Else
                Return CDec(Number).ToString("N1", CultureInfo.CreateSpecificCulture("vi-vn")).Split(",")(0)
            End If
            'If Number.IndexOf(",") > 0 Then
            '    Dim MangSo() As String = Number.Split(",")
            '    Dim PhanChan As String = MangSo(0)
            '    Dim PhanLe As String = MangSo(1)
            '    PhanChan = CDec(PhanChan).ToString("N1", CultureInfo.CreateSpecificCulture("vi-vn")).Split(",")(0)
            '    Return PhanChan & "," & PhanLe
            'Else
            '    Return CDec(Number).ToString("N1", CultureInfo.CreateSpecificCulture("vi-vn")).Split(",")(0)
            'End If
        Catch ex As Exception
            Throw
        End Try
    End Function
    Public Function DisplayNumberDatabase2Form(ByVal Number As String) As String
        Try
            If Number.IndexOf(".") > 0 Then
                Dim MangSo() As String = Number.Split(".")
                Dim PhanChan As String = MangSo(0)
                Dim PhanLe As String = MangSo(1)
                PhanChan = CDec(PhanChan).ToString("N1", CultureInfo.CreateSpecificCulture("vi-vn")).Split(".")(0)
                Return PhanChan & "," & PhanLe
            Else
                Return CDec(Number).ToString("N1", CultureInfo.CreateSpecificCulture("vi-vn"))
            End If
        Catch ex As Exception
            Throw
        End Try
    End Function
    Function ConvertCurencyToInt(ByVal Curency As String) As Integer
        Dim retInt As Integer
        If Curency = "" Then
            Return 0
        Else
            Curency = Curency.Split(",")(0).Replace(".", "")
            retInt = Integer.Parse(Curency)
            Return retInt
        End If
    End Function
    Function FormatNumber(ByVal Money As Single, Optional ByVal NoPercent As Boolean = False) As String
        Try
            If NoPercent Then
                Return CDec(Money.ToString).ToString("N", Globalization.CultureInfo.CreateSpecificCulture("vi-vn")).ToString().Replace(",00", "")
            Else
                Return CDec(Money.ToString).ToString("N", Globalization.CultureInfo.CreateSpecificCulture("vi-vn")).ToString()
            End If
        Catch ex As Exception
            Throw
        End Try
    End Function
    Function Num2Text(ByVal s As String, Optional ByVal Local As Boolean = False) As String
        Dim doctien As New hmweb.Services.cCommonFunction
        Dim sRet As String
        sRet = doctien.DocTienBangChu(s, " đồng")
        Return sRet
    End Function
    Function formatDate2VN(ByRef Ngay As String) As Boolean
        Dim aNgay As String() = Ngay.Split("/")
        Ngay = aNgay(1) & "/" & aNgay(0) & "/" & aNgay(2)
    End Function
    Function formatDateVN2String(ByVal Ngay As String) As String
        Dim aNgay As String() = Ngay.Split("/")
        Ngay = aNgay(1) & "/" & aNgay(0) & "/" & aNgay(2)
        Return Ngay
    End Function
    Function formatDateVN2String_print(ByRef Ngay As String) As Boolean
        Dim aNgay As String() = Ngay.Split("/")
        Ngay = "Ngày " & aNgay(1) & " Tháng " & aNgay(0) & " Năm " & aNgay(2)
    End Function
    Function formatDateVN2String_In(ByRef Ngay As String) As Boolean
        Dim aNgay As String() = Ngay.Split("/")
        Ngay = "              " & aNgay(1) & "                  " & aNgay(0) & "                " & aNgay(2).Replace("20", "")
    End Function
    Function NotCurencyFormat(ByVal Curency As String) As Boolean
        Dim dotPos As Integer = Curency.IndexOf(".")
        Dim commaPos As Integer = Curency.IndexOf(",")
        If dotPos < 0 Then Return True
        If dotPos >= commaPos Then Return True
        Return False
    End Function
    Public Sub ShowModalForm(ByVal Frm As Form, Optional ByVal MinimumBox As Boolean = True, Optional ByVal MaximumBox As Boolean = True)
        Frm.MaximizeBox = MaximumBox
        Frm.MinimizeBox = MinimumBox
        CenterForm(Frm)
        Frm.ShowDialog()
    End Sub
    Public Sub CenterForm(ByVal Frm As Form)
        Frm.StartPosition = FormStartPosition.CenterScreen
    End Sub
    Public Sub ShowError(ByVal ErrorReport As String, Optional ByVal button As Windows.Forms.MessageBoxButtons = MessageBoxButtons.OK, Optional ByVal Icon As Windows.Forms.MessageBoxIcon = MessageBoxIcon.Error)
        MessageBox.Show(ErrorReport, "", MessageBoxButtons.OK, Icon)
    End Sub
    Public Sub ShowDonHang(Optional ByVal Ex As Exception = Nothing)
        'write log
        If Not Ex Is Nothing Then
            Dim el As New ErrorsAndEvents.ErrorLogger
            Dim eventLog As New ErrorsAndEvents.EventLogger
            el.WriteToErrorLog(Ex.Message, Ex.StackTrace, "Error")
            eventLog.WriteToEventLog(Ex.Message, "DONASA", EventLogEntryType.Error, "QuanLyKhachHang")
        End If
    End Sub
    Public Sub ErrorConnectServer(Optional ByVal Ex As Exception = Nothing)
        'write log
        If Not Ex Is Nothing Then
            Dim el As New ErrorsAndEvents.ErrorLogger
            Dim eventLog As New ErrorsAndEvents.EventLogger
            el.WriteToErrorLog(Ex.Message, Ex.StackTrace, "Error")
            eventLog.WriteToEventLog(Ex.Message, "DONASA", EventLogEntryType.Error, "QuanLyKhachHang")
        End If
        '----
        MessageBox.Show("Không thể kết nối tới máy chủ.Vui lòng kiểm tra lại!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error)
    End Sub
    Public Sub ShowError(Optional ByVal Ex As Exception = Nothing)
        'write log
        If Not Ex Is Nothing Then
            Dim el As New ErrorsAndEvents.ErrorLogger
            Dim eventLog As New ErrorsAndEvents.EventLogger
            el.WriteToErrorLog(Ex.Message, Ex.StackTrace, "Error")
            eventLog.WriteToEventLog(Ex.Message, "DONASA", EventLogEntryType.Error, "QuanLyKhachHang")
        End If
        '----
        MessageBox.Show("Có lỗi trong quá trình xử lý.Xin vui lòng thực hiện lại", "Thong bao", MessageBoxButtons.OK, MessageBoxIcon.Error)
    End Sub
    '******************
    '*******************
    Public Function AutoGenKey(ByVal TableName As String, ByVal KeyLenght As Integer) As String
        Try
            Dim retKey As String = ""
            Dim dbConn As New OleDb.OleDbConnection
            Dim dataAccess As New DataAccess
            Dim dbCommand As OleDb.OleDbCommand
            Dim KeyReturn As String
            dataAccess.ConnectDatabase_DBAccess(dbConn)
            dbCommand = New OleDb.OleDbCommand("AutoGenKey", dbConn)
            dbCommand.CommandType = CommandType.StoredProcedure
            Dim iTableName As OleDb.OleDbParameter = dbCommand.Parameters.Add("TableName", OleDb.OleDbType.VarWChar)
            iTableName.Direction = ParameterDirection.Input
            iTableName.Value = TableName
            KeyReturn = dbCommand.ExecuteScalar()
            dbConn.Close()
            Dim aKeyReturn() As String = KeyReturn.Split(";")
            Dim PrefixKey As String = aKeyReturn(0)
            Dim NumKey As String = aKeyReturn(1)
            Select Case KeyLenght
                Case 4
                    Select Case NumKey
                        Case Is <= 9
                            retKey = PrefixKey & "000" & NumKey
                        Case Is <= 99
                            retKey = PrefixKey & "00" & NumKey
                        Case Is <= 999
                            retKey = PrefixKey & "0" & NumKey
                        Case Is <= 9999
                            retKey = PrefixKey & NumKey
                    End Select
                Case 5
                    Select Case NumKey
                        Case Is <= 9
                            retKey = PrefixKey & "0000" & NumKey
                        Case Is <= 99
                            retKey = PrefixKey & "000" & NumKey
                        Case Is <= 999
                            retKey = PrefixKey & "00" & NumKey
                        Case Is <= 9999
                            retKey = PrefixKey & "0" & NumKey
                        Case Is <= 99999
                            retKey = PrefixKey & NumKey
                    End Select
            End Select
            Return retKey
        Catch ex As Exception
            Throw ex
        End Try
    End Function
    Public Sub EmptyData(ByVal TextBox As TextBox)
        Try
            TextBox.BackColor = Color.FromArgb(192, 255, 255)
            TextBox.Focus()
        Catch ex As Exception
            ShowError()
        End Try
    End Sub
    Function Dollars(ByVal amount As Decimal, _
              Optional ByVal EmptyStringIfZero As Boolean = True) As String
        Dim result As String = String.Empty
        Select Case amount
            Case 0
                result = If(EmptyStringIfZero, String.Empty, "Zero ")
            Case 1 To 19
                result = Choose(amount, "One ", "Two ", "Three ", "Four ", _
         "Five ", "Six ", "Seven ", "Eight ", "Nine ", "Ten ", "Eleven ", _
         "Twelve ", "Thirteen ", "Fourteen ", "Fifteen ", "Sixteen ", _
         "Seventeen ", "Eighteen ", "Nineteen ")
            Case 20 To 99
                result = Choose(amount \ 10 - 1, "Twenty ", "Thirty ", _
         "Fourty ", "Fifty ", "Sixty ", "Seventy ", "Eighty ", _
         "Ninety ") & Dollars(amount Mod 10)
            Case 100 To 999
                result = Dollars(amount \ 100) & "Hundred" & IIf _
       (amount >= 200, "s ", " ") & Dollars(amount Mod 100)
            Case 1000 To 999999
                result = Dollars(amount \ 1000) & "Thousand" & IIf _
       (amount >= 2000, "s ", " ") & Dollars(amount Mod 1000)
            Case 1000000 To 999999999
                result = Dollars(amount \ 1000000) & "Million" & IIf _
       (amount >= 2000000, "s ", " ") & Dollars(amount Mod 1000000)
            Case Is >= 1000000000
                result = Dollars(amount \ 1000000000) & "Billion" & _
       IIf(amount >= 2000000000, "s", " ") & Dollars(amount Mod 1000000000)
        End Select
        Return result
    End Function

    Public Function Cents(ByVal amount As Decimal) As String
        Dim result As String = amount.ToString
        If result.Contains("."c) Then
            result = result.Substring(result.IndexOf("."c) + 1)
            Return " And " & Dollars(result) & " Cents"
        Else
            result = ""
        End If
    End Function
    Public Function UppercaseFirst(ByVal s As String) As String
        Try
            If String.IsNullOrEmpty(s) Then
                Return String.Empty
            End If
            Dim a() As Char = s.ToCharArray()
            a(0) = Char.ToUpper(a(0))
            Dim sRet As String = String.Empty
            sRet = sRet & a(0)
            For i As Integer = 1 To a.Length - 1
                sRet = sRet & a(i).ToString.ToLower()
            Next

            Return sret
        Catch ex As Exception
            Throw
        End Try
    End Function
    Public Sub ExportToFile(ByVal Path As String, ByVal oFileName As String, ByVal myContent As String)
        Dim file As FileStream
        If (IO.File.Exists(Path & "\" & oFileName)) Then
            file = New FileStream(Path & "\" & oFileName, FileMode.Append, FileAccess.Write, FileShare.Read, 8)
        Else
            file = New FileStream(Path & "\" & oFileName, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite, 8)
        End If

        Dim sw As New StreamWriter(file, System.Text.Encoding.Unicode)
        If (IO.File.Exists(Path & "\" & oFileName)) Then
            sw.BaseStream.Seek(0, SeekOrigin.End)
        Else
            sw.BaseStream.Seek(0, SeekOrigin.Begin)
        End If
        sw.Write(myContent)
        sw.Close()
    End Sub
End Module

